import {createRouter, createWebHashHistory} from "vue-router";
import routes, {generatorRouters} from './routers'
import {useStore} from "@/store";


const modules = import.meta.glob('../views/**/**.vue')

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

const LOGIN_STATE = {
  IS_LOGIN: 'Login'
}

router.beforeEach(async (to, from, next) => {
  const store = useStore()
  // 修改后
  const token = sessionStorage.getItem('token')
  // 未登录跳转登录页
  if (!token && to.name !== LOGIN_STATE.IS_LOGIN) {
    next({name: 'Login'})
  }
  // 已登录跳转登录页
  else if (token && to.name === LOGIN_STATE.IS_LOGIN) {
    next({name: 'Home'})
  }
  // 正常跳转
  else {
    // 进入时，如果没有获取导航菜单，就去调用接口获取一遍
    if (token && store.layout.menuList.length === 0) {
      try {
        await store.layout.getMenuList()
        const newRoutes = generateRouter(store.layout.userRouters)
        const layout = routes.find((item) => {
          return item.name === 'Layout'
        })
        if (layout) {
          // 修改后：保留原始路由，并添加动态路由
          layout.children = [...layout.children, ...newRoutes]
          layout.children = [...layout.children]
          router.addRoute(layout)
          return router.replace(to.path)
        }
      } catch (error) {
        // console.error('获取菜单失败:', error)
      }
    }
    next()
  }
})

// 将获取到的导航菜单，转换为路由，并添加到路由中
/**
 * 根据用户路由配置生成路由表
 * @param {Array} userRouters - 用户路由配置数组
 * @returns {Array} 生成后的路由表
 */
const generateRouter = (userRouters) => {
  return userRouters.map((router) => {
    // 判断是否为父级路由（pid为0且存在子路由）
    const isParent = router.pid === 0 && router.children
    // 确保路由路径以斜杠开头
    const routePath = router.path.startsWith('/') ? router.path : `/${router.path}`
    // 构建路由对象
    const routes = {
      path: routePath,
      name: router.name,
      children: [],
      // 动态导入组件，优先使用本地模块
      component: modules[`../views${routePath}/index.vue`] || (() => import(`../views${routePath}/index.vue`))
    }

    // 如果是父级路由且有子路由，设置重定向到第一个子路由
    if (isParent && router.children[0]) {
      routes.redirect = router.children[0].path
    }
    // 如果路由存在子路由，递归处理子路由
    if (routes && router.children) {
      routes.children = generateRouter(router.children)
    }
    return routes
  })
}

export default router

